package vlc;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.jna.NativeLibrary;

import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.headless.HeadlessMediaPlayer;

/**
 * Servlet implementation class VlcStream
 */
public class VlcStream extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private StreamContext streamInstance;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public VlcStream() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init() throws ServletException {
		super.init();
		NativeLibrary.addSearchPath("vlc", getServletContext().getRealPath("WEB-INF/lib"));
		NativeLibrary.addSearchPath("libvlc", getServletContext().getRealPath("WEB-INF/lib"));
		
		streamInstance = StreamContext.getInstance();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String roleName = (String) session.getAttribute("VLCSA_role");
		if ("VLCSA Admin".equals(roleName)) {
			streamInstance.stopStream();
		}
		getServletConfig().getServletContext().getRequestDispatcher("/adminTool.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			streamInstance.setStreamUrl(request.getParameter("s_adress"));
			streamInstance.setMrl(request.getParameter("s_mrl"));
			streamInstance.setCodec(request.getParameter("codec"));
			streamInstance.startStream();
			//Thread.currentThread().join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
	}

}
